import React,{Component} from "react";
import Tipmsg from "../../components/tipmsg"

import "./index.css"


import {createSubPost,postVideo,postImg,delPost} from "../../api/course.js"
import config from "../../api/config.js"


function loadImg(fr){
    return new Promise(function(resolve,reject){
         fr.onload = function(e){
            resolve(e.target.result)   
        }
    })
}


class Index extends Component{
    constructor(props){
        super(props);
        this.state = {
            title:"",
            imglist:[],
            filelist:[],
            videoSrc:"",
            videoFile:"",
            nowIndex:0,
            showLoading:false,
            num:0,
            loadtext:"",
            msg:"",
            showTip:false
        }
    }

    closeHandl(){
      this.setState({showTip:false})
    }

    async changeImg(ev){
            var files = ev.target.files;
           
            var length = files.length;
            var _this = this;
            
            if(length<=9){
              for( var i = 0 ; i < length ; i++ ){

                    var fr = new FileReader();
            
                    fr.readAsDataURL(files[i]);//读取文件
                    
                    let dataImg = await loadImg(fr);
                    this.state.filelist.push(files[i]);
                    this.state.imglist.push(dataImg);
                    this.setState({
                       imglist:this.state.imglist.slice(0,9),
                       filelist:this.state.filelist.slice(0,9),
                       nowIndex:0
                    })   


                    
              }
            }else{
                for( var i = 0 ; i < 9 ; i++ ){

                    var fr = new FileReader();
            
                    fr.readAsDataURL(files[i]);//读取文件
                    
                    let dataImg = await loadImg(fr);
                    this.state.filelist.push(files[i])
                    this.state.imglist.push(dataImg);
                    this.setState({
                       imglist:this.state.imglist.slice(0,9),
                       filelist:this.state.filelist.slice(0,9),
                       nowIndex:0
                    })   
                }
            }


            
    }

    
    changeVideo(ev){
        var _this = this;
        var files = ev.target.files;
       
        var fr = new FileReader();

        fr.readAsDataURL(files[0]);//读取文件
        this.setState({
            videoFile:files[0]
        })
        fr.onload = function(e){
      
            _this.setState({
                videoSrc:fr.result,
                nowIndex:1
            })      

        }
    }

    delHandl(index){
        this.state.imglist.splice(index,1);
        this.state.filelist.splice(index,1);
        this.setState({
            imglist:this.state.imglist,
            filelist:this.state.filelist
        })
    }


    sendHandl(){

         let {nowIndex,filelist,videoFile,imglist} = this.state;
         let {id} = this.props.match.params;
         let token = JSON.parse(localStorage.getItem("courseUserinfo")).AccessToken;
         let maxSizeVideo = 1024*30; 
         let maxSizeimg = 1024*10;
         /*
         console.log(filelist)
         return*/
        if(nowIndex==1){
            if(videoFile==""){
                this.setState({
                     msg:"请选择视频",
                     showTip:true
                })
                return;
            }
            if(videoFile.size/1024>maxSizeVideo){
                this.setState({
                    msg:"上传视频不超过30M",
                    showTip:true
                })
                return false;
            }
        }else if(nowIndex==0){
                 

                if(filelist.length==0){
                    this.setState({
                        msg:"请选择至少一张图片",
                        showTip:true
                    })
                  return;
                }

                
                let count = 0;
                filelist.forEach(item=>{
                    if(item.size/1024>maxSizeimg){
                        count++;
                    }
                    
                })
           
                if(count>0){
                 
                    this.setState({
                     msg:"上传图片大小不超过10M",
                     showTip:true
                    })
                    return false;
                }
         }
         
        if(nowIndex==1){
            this.setState({
                    showLoading:true,
                    loadtext:"上传中..."
            }) 
        }else{
            this.setState({
                showLoading:true,
                loadtext:"上传图片进度第0/"+filelist.length+"张"
            }) 
        }
            

         createSubPost(token,id,{
            "Title":this.state.title,
            "Type" : 31,
            "IsPublished":true,
            "CategoryId": config.CategoryId,
         }).then(res=>{
            
            if(nowIndex==1){  //选择了视频
               
                var formdata = new FormData();
                formdata.append('image',videoFile);
                postVideo(token,res.data.PostId,formdata)
                .then(res=>{
                     this.setState({
                        showLoading:false,
                        loadtext:""
                     })
                     this.props.history.goBack();
                }).catch(err=>{
                    
                    this.setState({
                     msg:"上传失败",
                     showTip:true
                    })
                })
           
            }else if(nowIndex==0){  //选择了图片
               
                let num = 0;
                let postid = res.data.PostId;
                filelist.forEach(item=>{
                     var formdata = new FormData();
                     formdata.append('image',item);
                     postImg(token,postid,formdata)
                     .then(res=>{
                           num++;
                           console.log(num)
                           this.setState({
                                loadtext:"上传图片进度第"+num+"/"+filelist.length+"张"
                           }) 
                          if(num==filelist.length){
                             this.setState({
                                  showLoading:false
                             })
                             this.props.history.goBack();
                          }
                     }).catch(err=>{
                        console.log(err.response.data.ErrorMessage)
                        this.setState({
                            msg:"内容不当，请删除重交"||"上传失败",
                            showTip:true,
                            showLoading:false
                        },()=>{
                            delPost(token,postid).then(res=>{
                                console.log(res)
                            })
                        })
                     })
                })
                
            }

         }).catch(err=>{
            console.log(err.response.data)
            this.setState({
                msg:err.response.data.ErrorMessage,
                showTip:true,
                showLoading:false
            })
         })
       

    }


	render(){
        let {imglist,nowIndex,videoSrc,title} = this.state;
		return(
            <div className="postwork">
                <div className="postwork-header">
                    <span className="cancel" onClick={()=>{this.props.history.goBack()}}>取消</span>
                    上传作业
                    <span className="sendbtn" onClick={this.sendHandl.bind(this)}>发布</span>
                </div>

                <p className="title"><input type="text" placeholder="请输入标题" value={title} onChange={(ev)=>{
                      this.setState({title:ev.target.value})
                }}/></p>
                
                
                <div className="imglist" style={{"display":nowIndex==0?"block":"none"}}>
                     <ul>
                        {
                            imglist.map((item,index)=>{
                                return <li key={index}>
                                <img src={item} alt=""/>
                                <span className="del" onClick={this.delHandl.bind(this,index)}></span>
                                </li>
                            })
                        }
                     </ul>
                </div>

                <div className="videobox" style={{"display":nowIndex==1?"block":"none"}}>
                     <video src={videoSrc} controls></video>
                </div>


                <div className="btns">
                    <span className="photo">
                       <input type="file" multiple accept="image/*" onChange={this.changeImg.bind(this)}/>
                    </span>

                    <span className="video">
                       <input type="file"  accept="video/mp4" onChange={this.changeVideo.bind(this)}/>
                    </span>
                </div>

                {this.state.showLoading?<div className="loading"><p>{this.state.loadtext}</p></div>:null}
                {this.state.showTip?<Tipmsg closeHandl={this.closeHandl.bind(this)} msg={this.state.msg}/>:null}
            </div>
		)
	}
}

export default Index